package com.ruoyi.campus.service.impl;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.campus.domain.Area;
import com.ruoyi.campus.mapper.AreaMapper;
import com.ruoyi.campus.service.IAreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 区域信息Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-06-29
 */
@Service
public class AreaServiceImpl implements IAreaService
{
    @Autowired
    private AreaMapper areaMapper;

    /**
     * 查询区域信息
     * 
     * @param areaId 区域信息主键
     * @return 区域信息
     */
    @Override
    public Area selectAreaByAreaId(Long areaId)
    {
        return areaMapper.selectAreaByAreaId(areaId);
    }

    /**
     * 查询区域信息列表
     * 
     * @param area 区域信息
     * @return 区域信息
     */
    @Override
    public List<Area> selectAreaList(Area area)
    {
        return areaMapper.selectAreaList(area);
    }

    /**
     * 新增区域信息
     * 
     * @param area 区域信息
     * @return 结果
     */
    @Override
    @CacheEvict(value = {"areaTreeCache", "areaTreeBuildCache", "areaTreeSelectCache"}, allEntries = true)
    public int insertArea(Area area)
    {
        // 如果父节点ID为空或为0，说明是根节点
        if (area.getParentId() == null || area.getParentId() == 0)
        {
            area.setAncestors("0");
        }
        else
        {
            Area info = areaMapper.selectAreaByAreaId(area.getParentId());
            // 如果父节点不存在
            if (info == null)
            {
                throw new RuntimeException("父节点不存在");
            }
            // 如果父节点不为正常状态,则不允许新增子节点
            if (!Area.NORMAL.equals(info.getStatus()))
            {
                throw new RuntimeException("区域停用，不允许新增");
            }
            area.setAncestors(info.getAncestors() + "," + area.getParentId());
        }
        area.setCreateTime(DateUtils.getNowDate());
        return areaMapper.insertArea(area);
    }

    /**
     * 修改区域信息
     * 
     * @param area 区域信息
     * @return 结果
     */
    @Override
    @CacheEvict(value = {"areaTreeCache", "areaTreeBuildCache", "areaTreeSelectCache"}, allEntries = true)
    public int updateArea(Area area)
    {
        if (area.getAreaId() == null) {
            return 0;
        }
        Area newParentArea = areaMapper.selectAreaByAreaId(area.getParentId());
        Area oldArea = areaMapper.selectAreaByAreaId(area.getAreaId());
        if (StringUtils.isNotNull(newParentArea) && StringUtils.isNotNull(oldArea))
        {
            String newAncestors = newParentArea.getAncestors() + "," + newParentArea.getAreaId();
            String oldAncestors = oldArea.getAncestors();
            area.setAncestors(newAncestors);
            updateAreaChildren(area.getAreaId(), newAncestors, oldAncestors);
        }
        area.setUpdateTime(DateUtils.getNowDate());
        return areaMapper.updateArea(area);
    }

    /**
     * 批量删除区域信息
     * 
     * @param areaIds 需要删除的区域信息主键
     * @return 结果
     */
    @Override
    @CacheEvict(value = {"areaTreeCache", "areaTreeBuildCache", "areaTreeSelectCache"}, allEntries = true)
    public int deleteAreaByAreaIds(String areaIds)
    {
        String[] arr = Convert.toStrArray(areaIds);
        if (arr.length == 0) {
            return 0;
        }
        return areaMapper.deleteAreaByAreaIds(arr);
    }

    /**
     * 删除区域信息信息
     * 
     * @param areaId 区域信息主键
     * @return 结果
     */
    @Override
    @CacheEvict(value = {"areaTreeCache", "areaTreeBuildCache", "areaTreeSelectCache"}, allEntries = true)
    public int deleteAreaByAreaId(Long areaId)
    {
        return areaMapper.deleteAreaByAreaId(areaId);
    }

    /**
     * 查询区域树形结构列表
     * 
     * @param area 区域信息
     * @return 区域树形结构列表
     */
    @Override
    @Cacheable(value = "areaTreeCache", key = "#area.toString()", unless = "#result == null || #result.isEmpty()")
    public List<Area> selectAreaTreeList(Area area)
    {
        return areaMapper.selectAreaTreeList(area);
    }

    /**
     * 根节点的父ID常量
     */
    private static final Long ROOT_PARENT_ID = 0L;

    /**
     * 构建前端所需要的树结构
     * 
     * @param areas 区域列表
     * @return 树结构列表
     */
    @Override
    @Cacheable(value = "areaTreeBuildCache", key = "#areas.hashCode()", unless = "#result == null || #result.isEmpty()")
    public List<Area> buildAreaTree(List<Area> areas)
    {
        if (areas == null || areas.isEmpty())
        {
            return new ArrayList<Area>();
        }
        
        List<Area> returnList = new ArrayList<Area>();
        // 使用HashSet提高查找性能
        Set<Long> areaIdSet = new HashSet<Long>();
        for (Area area : areas)
        {
            areaIdSet.add(area.getAreaId());
        }
        
        for (Area area : areas)
        {
            // 修复顶级节点判断逻辑：parentId为null、0或不在当前列表中的都是顶级节点
            if (isRootNode(area, areaIdSet))
            {
                recursionFn(areas, area);
                returnList.add(area);
            }
        }
        
        if (returnList.isEmpty())
        {
            returnList = areas;
        }
        return returnList;
    }

    /**
     * 判断是否为根节点
     * 
     * @param area 区域对象
     * @param areaIdSet 所有区域ID的集合
     * @return 是否为根节点
     */
    private boolean isRootNode(Area area, Set<Long> areaIdSet)
    {
        return area.getParentId() == null 
            || ROOT_PARENT_ID.equals(area.getParentId()) 
            || !areaIdSet.contains(area.getParentId());
    }

    /**
     * 构建前端所需要下拉树结构
     * 
     * @param areas 区域列表
     * @return 下拉树结构列表
     */
    @Override
    @Cacheable(value = "areaTreeSelectCache", key = "#areas.hashCode()", unless = "#result == null || #result.isEmpty()")
    public List<Area> buildAreaTreeSelect(List<Area> areas)
    {
        List<Area> areaTrees = buildAreaTree(areas);
        return areaTrees.stream().map(this::copyAreaWithChildren).collect(Collectors.toList());
    }

    /**
     * 深拷贝区域对象，包括children属性
     * 
     * @param original 原始区域对象
     * @return 拷贝后的区域对象
     */
    private Area copyAreaWithChildren(Area original)
    {
        Area copy = new Area(original);
        if (original.getChildren() != null && !original.getChildren().isEmpty())
        {
            List<Area> childrenCopy = original.getChildren().stream()
                .map(this::copyAreaWithChildren)
                .collect(Collectors.toList());
            copy.setChildren(childrenCopy);
        }
        return copy;
    }

    /**
     * 检查区域名称是否唯一
     * 
     * @param area 区域信息
     * @return 结果
     */
    @Override
    public String checkAreaNameUnique(Area area)
    {
        Long areaId = StringUtils.isNull(area.getAreaId()) ? -1L : area.getAreaId();
        Area info = areaMapper.checkAreaNameUnique(area);
        if (StringUtils.isNotNull(info) && info.getAreaId().longValue() != areaId.longValue())
        {
            return "1";
        }
        return "0";
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<Area> list, Area t)
    {
        // 得到子节点列表
        List<Area> childList = getChildList(list, t);
        t.setChildren(childList);
        for (Area tChild : childList)
        {
            if (hasChild(list, tChild))
            {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<Area> getChildList(List<Area> list, Area t)
    {
        List<Area> tlist = new ArrayList<Area>();
        Iterator<Area> it = list.iterator();
        while (it.hasNext())
        {
            Area n = (Area) it.next();
            if (StringUtils.isNotNull(n.getParentId()) && n.getParentId().longValue() == t.getAreaId().longValue())
            {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<Area> list, Area t)
    {
        return getChildList(list, t).size() > 0 ? true : false;
    }

    /**
     * 修改子元素关系
     * 
     * @param areaId 被修改的区域ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateAreaChildren(Long areaId, String newAncestors, String oldAncestors)
    {
        List<Area> children = areaMapper.selectChildrenAreaById(areaId);
        for (Area child : children)
        {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0)
        {
            areaMapper.updateAreaChildren(children);
        }
    }
}
